const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const { koaBody } = require("koa-body");
const path = require("path");
const koastatic = require("koa-static");
const cors = require("koa2-cors");
const connectDB = require("./config/database");

const index = require("./routes/index");
const users = require("./routes/users");
const upload = require("./routes/upload");

// error handler
onerror(app);
app.use(cors());
connectDB();

//! 注意的是通常静态服务都是在最前面
app.use(koastatic(path.join(__dirname, "/public")));

// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
app.use(json());
app.use(logger());

app.use(
  views(__dirname + "/views", {
    extension: "pug",
  })
);

app.use(koastatic(path.join(__dirname, "public"))); //这个public以下的路径就是生成的url。

//图片
app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 200 * 1024 * 1024,
      uploadDir: path.join(__dirname, "/public/upload"),
      // 上传目录，意思是说上传到当前项目的/public/upload目录下/ 是否保留拓展名
      keepExtensions: true,
    },
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());
app.use(upload.routes(), upload.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;
